from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from ..db import get_db
from .. import models, schemas
from ..security import get_current_user

router = APIRouter()

@router.post("/", response_model=schemas.TagOut)
def create_tag(payload: schemas.TagCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    t = models.Tag(name=payload.name, color=payload.color, owner_id=current.id)
    db.add(t)
    db.commit()
    db.refresh(t)
    return t

@router.post("", response_model=schemas.TagOut)
def create_tag_noslash(payload: schemas.TagCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    """Alias without trailing slash to avoid 307 redirect from /api/tags to /api/tags/ on POST."""
    return create_tag(payload, db, current)


@router.get("/", response_model=List[schemas.TagOut])
def list_tags(db: Session = Depends(get_db), current=Depends(get_current_user)):
    return db.query(models.Tag).filter(models.Tag.owner_id == current.id).all()


@router.get("", response_model=List[schemas.TagOut])
def list_tags_noslash(db: Session = Depends(get_db), current=Depends(get_current_user)):
    """Alias without trailing slash to avoid 307 redirect between /api/tags and /api/tags/."""
    return list_tags(db, current)

@router.put("/{tag_id}", response_model=schemas.TagOut)
def update_tag(tag_id: int, payload: schemas.TagCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    t = db.query(models.Tag).filter(models.Tag.id == tag_id, models.Tag.owner_id == current.id).first()
    if not t:
        raise HTTPException(status_code=404, detail="Tag not found")
    t.name = payload.name
    t.color = payload.color
    db.commit()
    db.refresh(t)
    return t

@router.delete("/{tag_id}")
def delete_tag(tag_id: int, db: Session = Depends(get_db), current=Depends(get_current_user)):
    t = db.query(models.Tag).filter(models.Tag.id == tag_id, models.Tag.owner_id == current.id).first()
    if not t:
        raise HTTPException(status_code=404, detail="Tag not found")
    db.delete(t)
    db.commit()
    return {"ok": True}
